<?php

namespace App\Http\Controllers\Admin;

use App\Library\R;
use App\Models\Tag;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class TagController extends Controller
{
    /**
     * Display a listing of the resource.
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        return view('admin.tag.index');
    }

    public function data(Request $request)
    {
        $res = Tag::orderBy('id', 'desc')->orderBy('sort', 'desc')->paginate($request->get('limit', 30))->toArray();

        return $this->table($res['data'], $res['total']);
    }

    /**
     * Show the form for creating a new resource.
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        return view('admin.tag.create');
    }

    /**
     * Store a newly created resource in storage.
     * @param  \Illuminate\Http\Request $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $this->validate($request, [
            'name' => 'required|string',
            'sort' => 'required|numeric'
        ]);
        if (Tag::create($request->all())) {
            return redirect(route('admin.tag'))->with(['status' => '添加完成']);
        }
        return redirect(route('admin.tag'))->with(['status' => '系统错误']);
    }

    /**
     * Display the specified resource.
     * @param  int $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     * @param  int $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        $tag = Tag::findOrFail($id);
        return view('admin.tag.edit', compact('tag'));
    }

    /**
     * Update the specified resource in storage.
     * @param  \Illuminate\Http\Request $request
     * @param  int $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        $this->validate($request, [
            'name' => 'required|string',
            'sort' => 'required|numeric'
        ]);
        $tag = Tag::findOrFail($id);
        if ($tag->update($request->only(['name', 'sort']))) {
            return redirect(route('admin.tag'))->with(['status' => '更新成功']);
        }
        return redirect(route('admin.tag'))->withErrors(['status' => '系统错误']);
    }

    /**
     * Remove the specified resource from storage.
     * @param  int $id
     * @return \Illuminate\Http\Response
     */
    public function destroy(Request $request)
    {
        $ids = $request->get('ids');
        if (empty($ids)) {
            return $this->error('请选择删除项');
        }
        if (Tag::destroy($ids)) {
            return $this->success('删除成功');
        }
        return $this->error('删除失败');
    }
}
